<template>
  <div>
    <a-card>
      <div ref="lineChart1" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart2" v-if="!searchData.studentId" :style="{width:'100%',height:'368px'}"></div>
    </a-card>
  </div>
</template>
<script>

import { getAction } from '@/api/manage'
export default
{
  name: 'temp',
  data() {
    return {
      url: {
        list: 'health/skTemperatureRecord/getTotalTemperatureStatistical',
        stuList: 'health/skTemperatureRecord/getStudentTemperature'
      },
      searchData: {
        dateType: '',
        semesterId: '',
        classId: '',
        studentId: ''
      },
      color:["#0CDF8A","#3EACE5"],
      detailData: {},
      numList:[]
    }
  },
  props:["dataForm","semesterName","className"],
  components: {},
  filters: {},
  
  computed: {},
  
  created() {
  },
  
  activated() {
  },

  mounted() {
    this.load()
  },

  methods: {
    load() {
      const dataForm = this.dataForm
      console.log(this.dataForm);
      this.numList = []
      // 查询列表数据
      this.searchData.dateType = dataForm.dateType
      this.searchData.semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId
      this.searchData.classId = dataForm.classId ? dataForm.classId : undefined
      this.searchData.studentId = dataForm.studentId ? dataForm.studentId : undefined
      if(dataForm.studentId) {
        this.studentChart()
      }else if(dataForm.classId) {
        this.allChart();
        this.classChart();
      }else{
        this.allChart();
        this.allClassChart();
      }
    },
    allChart() {
      let params = {
        byType: 'month',
        semesterId: this.searchData.semesterId,
        classId: this.searchData.classId,
        // statisticalScope: 'class'
      }
      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [];//异常次数

          // 每月
          const monthColumns = this.dataForm.monthColumns;
          for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
            const rowString = monthColumns[rowIndex].toString();
            categorys.push(rowString);

            const monthData = res.result.find(item => item.statisticalDate == rowString);
            if (monthData){
              xData.push(monthData.abnormalNum);
            } else {
              xData.push(0);
            }
          }
          this.initLineChart(this.$refs.lineChart1, '月体温异常幼儿人数统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    allClassChart() {
      let params = {
        byType: 'all',
        semesterId: this.searchData.semesterId,
        statisticalScope: 'class'
      }
      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [];//异常次数
            console.log('classList', this.dataForm.classList)
          const classList = this.dataForm.classList.filter(item => { return item.id != ''});
          classList.forEach(el => {
            categorys.push(el.className);

            const classData = res.result.find(item => item.classId == el.id)
            if(classData){
              xData.push(classData.abnormalNum)
            } else {
              xData.push(0);
            }
          })
          this.initBarChart(this.$refs.lineChart2, '各班体温异常人数统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    classChart() {
      let params = {
        byType: 'all',
        semesterId: this.searchData.semesterId,
        classId: this.searchData.classId,
        statisticalScope: 'student'
      }
      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [];//异常次数
          res.result.forEach(el => {
            categorys.push(el.studentName);
            xData.push(el.abnormalNum)
          })
          this.initBarChart(this.$refs.lineChart2, '幼儿学期体温异常天数统计', categorys, xData, '天数');
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    studentChart() {
      let params = {
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
      }
      getAction(this.url.stuList, params).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData = [];//异常次数

          // 每月
          const monthColumns = this.dataForm.monthColumns;
          for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
            const rowString = monthColumns[rowIndex].toString();
            categorys.push(rowString);

            const monthData = res.result.find(item => item.statisticalDate == rowString);
            if (monthData){
              xData.push(monthData.abnormalNum);
            } else {
              xData.push(0);
            }
          }
          this.initLineChart(this.$refs.lineChart1, '月体温异常天数统计', categorys, xData, '天数');
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    initLineChart(el, title, categorys, xData) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }

      const legendTitle = ['人数'];
      var optionChart = {
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.semesterName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          // y: 'top', //延Y轴居中 
          // x: 'right', //居右显示
          right: '20%'
        },
        xAxis: {
          type: 'category',
          data: categorys
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: legendTitle[0],
            data: xData,
            type: 'line',
            itemStyle: {
              normal: {
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            },
            smooth: true
          }
        ]
      };

      myChartSports.setOption(optionChart);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    initBarChart(el, title, categorys, xData, legend='人数') {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }

      const legendTitle = [legend];
      var optionChart = {
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.semesterName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          // y: 'top', //延Y轴居中 
          // x: 'right', //居右显示
          right: '20%'
        },
        xAxis: {
          type: 'category',
          data: categorys
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: legendTitle[0],
            data: xData,
            type: 'bar',
            barWidth: 8,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: this.color[0]
                  },
                  {
                    offset: 1,
                    color: this.color[1]
                  }
                ]),
                label : {
                  show: true // 显示数据
                },
              }
            },
            smooth: true
          }
        ]
      };

      myChartSports.setOption(optionChart);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    handleEmit(){
      this.numList.push(true);
      if(this.dataForm.studentId) {
        if (this.numList.length == 1) {
          this.$emit("ok")
        }
      }else if(this.dataForm.classId) {
        if (this.numList.length == 2) {
          this.$emit("ok")
        }
      }else{
        if (this.numList.length == 2) {
          this.$emit("ok")
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
</style>